package saas.provider.service.controller;

import com.baozun.saas.core.context.TenantContext;
import com.baozun.tenant.core.context.ServiceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @title: MainController
 * @description: 主控制器
 * @author: guan.xin
 * @create: 2021-11-12 15:33
 * @since: JDK8
 */

@Slf4j
@RequestMapping("/main")
@RestController
public class MainController {

    @GetMapping(value = "/get")
    public String getHello(@RequestParam String empCode) {
        log.info("访问测试日志：{}, {}", "hello world!", empCode);
        return TenantContext.getCurrentSaaSTenantCode();
    }

    @PostMapping(value = "/remote")
    public String remote(@RequestParam String empCode) {
        log.info("访问测试日志：{}, {}", "hello world!", empCode);
        log.info("getRemoteSaaSTenantFlagContext, {}", ServiceContextHolder.getRemoteSaaSTenantFlagContext());
        return TenantContext.getCurrentSaaSTenantCode();
    }

    @GetMapping(value = "/remote")
    public String remote2(@RequestParam String empCode) {
        log.info("访问测试日志：{}, {}", "hello world!", empCode);
        log.info("getRemoteSaaSTenantFlagContext, {}", ServiceContextHolder.getRemoteSaaSTenantFlagContext());
        return TenantContext.getCurrentSaaSTenantCode();
    }

    @PostMapping(value = "/push")
    public void push() throws UnsupportedEncodingException {

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost("http://localhost:9090/main/get");

            ContentType contentType = ContentType.create("text/xml", Charset.forName("UTF-8"));
            ByteArrayEntity byteArrayEntity = new ByteArrayEntity("IT后端测试店铺Converse".getBytes("UTF-8"), contentType);
            httpPost.setEntity(byteArrayEntity);

            HttpResponse result = httpClient.execute(httpPost);
            log.info("返回码：" + result.getStatusLine().getStatusCode());
            String resultStr = EntityUtils.toString(result.getEntity());
            log.info("返回内容：" + resultStr);
        } catch (Exception e) {
            log.error("错误信息:", e);
        }

    }
}
